﻿/// <reference path="../jquery-1.6.4.js"/>

(function ($1, undefined) {
    var $CurrJqgrid;
    if (typeof ($.jqgrid) === "undefined")
        $.jqgrid = {};
    $.extend($.jqgrid, { getCurr: function() {
        return $CurrJqgrid || $('.ui-jqgrid-btable');
    }});
    $.jqgrid.unobtrusive = {
        getSeachRules: function ($container) {
            var ruleArr = [];
            $container.find(':input[data-searchField]').each(function () {
                var rule = {}, $self = $(this);
                if ($self.val() == '') return true;
                rule['field'] = $self.attr('data-searchField');
                rule['op'] = $self.attr('data-searchOp');
                rule['data'] = $self.val();
                ruleArr.push(rule);
            });
            return { groupOp: 'AND', rules: ruleArr };
        },
        autoBinder: function ($container) {
            if ($CurrJqgrid === undefined && $('.ui-jqgrid-btable').size() > 0)
                $CurrJqgrid = $('.ui-jqgrid-btable');
            $container.find('.ui-jqgrid-search').unbind('click.jqgrid-search').bind('click.jqgrid-search', function () {
                var filtersStr = JSON.stringify($.jqgrid.unobtrusive.getSeachRules($container)),
                    postData = $CurrJqgrid.jqGrid('getGridParam', 'postData');
                $.extend(postData, { filters: filtersStr });
                $CurrJqgrid.jqGrid("setGridParam", { search: true }).trigger("reloadGrid", [{ page: 1}]);
                return false;
            });
            $container.find('.ui-jqgrid-create').unbind('click.jqgrid-create').bind('click.jqgrid-create', function () {
                $.bs.showDialog({ url: this.href, title: this.title });
                return false;
            });
            $container.find('.ui-button').button();
        }
    };

    $(document).ready(function () {
        $.jqgrid.unobtrusive.autoBinder($('.searchTable'));
    });
})(jQuery);